import 'dart:convert';
import 'dart:io';

import 'package:base_app/commons/constants/app_constant.dart';
import 'package:base_app/commons/manager/logger_manager.dart';
import 'package:base_app/utils/file_util.dart';
import 'package:base_app/utils/permission_util.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'base_handler.dart';

class VoiceRecordHandler extends BaseHandler {

  @override
  String name = "voiceRecord";

  FlutterSoundRecorder recorderModule = FlutterSoundRecorder();
  FlutterSoundPlayer playerModule = FlutterSoundPlayer();

  @override
  void handler(dynamic data, dynamic responseCallback) async {
    bool permission = await PermissionUtil.getPermissionStatus(Permission.microphone);
    if(!permission) {
      return;
    }
    String type = 'start';
    if(data != null && data.containsKey('type')) {
      type = data['type'];
    }
    if(type == 'start') {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      //用户允许使用麦克风之后开始录音
      Directory tempDir = await getTemporaryDirectory();
      var time = DateTime.now().millisecondsSinceEpoch;
      String path = '${tempDir.path}/$time${ext[Codec.aacADTS.index]}';
      await recorderModule.openRecorder();
      await recorderModule.startRecorder(toFile: path, codec: Codec.aacADTS);
      await prefs.setString('voiceRecord', await FileUtil.setFileFromLocalStorage(path));
    } else if(type == 'stop') {
      String? url = await stopRecord();
      responseCallback(jsonEncode({'url': url}));
    } else if(type == 'pause'){
      await recorderModule.pauseRecorder();
    } else if(type == 'resume'){
      await recorderModule.resumeRecorder();
    } else if(type == 'play') {
      if(data != null && data.containsKey('url')) {
        playVoice(data['url']);
      }
    }
  }

  Future<String?> stopRecord() async {
    try {
      await recorderModule.stopRecorder();
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      return prefs.getString('voiceRecord');
    } catch (err) {
      LoggerManager().error('结束录音出错 err: $err');
    }
    return null;
  }

  void playVoice(url) async {
    try {
      if (url.contains('http')) {
        await playerModule.openPlayer();
        await playerModule.startPlayer(fromURI: url);
      } else if(url.startsWith(AppConstant.schemePrefix)) {
        url = url.replaceAll(AppConstant.schemePrefix, '');
        File file = await FileUtil.getFileFromLocalStorage(url);
        if (await FileUtil.fileExists(file.path)) {
          if (playerModule.isPlaying) {
            playerModule.stopPlayer();
          }
          await playerModule.openPlayer();
          await playerModule.startPlayer(fromURI: file.path);
        }
      }
    } catch (err) {
      LoggerManager().error("播放语音出错 err: $err");
    }
  }
}